<?php


namespace app\admin\controller;


use app\common\model\RecommendVod;

class Recommend extends Base
{
    public $fileName = 'tuijian.json';

    public function __construct()
    {
        parent::__construct();
    }

    protected function getJsonData()
    {
        $filePath = ROOT_PATH . $this->fileName;
        $data = file_get_contents($filePath);
        $data = json_decode($data, true);
        return $data;
    }

    protected function putJsonData($data)
    {
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $filePath = ROOT_PATH . $this->fileName;
        $data = file_put_contents($filePath, $data);
    }

    public function index()
    {
        $param = input();
        $page = intval($param['page']) < 1 ? 1 : $param['page'];
        $limit = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $offset = $limit * ($page - 1);
        $total = db('recommend')->count();
        $list = db('recommend')->order('sort', 'asc')->order('time_added', 'desc')->limit(
            $offset,
            $limit
        )->select();
        $list = [
            'code' => 1,
            'msg' => '数据列表',
            'page' => $page,
            'pagecount' => ceil($total / $limit),
            'limit' => $limit,
            'total' => $total,
            'list' => $list
        ];

        $this->assign('list', $list['list']);
        $this->assign('total', $list['total']);
        $this->assign('page', $list['page']);
        $this->assign('limit', $list['limit']);
        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);
        return $this->fetch('admin@recommend/index');
    }

    public function vodindex()
    {
        $xilie_id = input('xilie_id', 0, 'intval');

        $recommend = db('recommend')->where('id', $xilie_id)->find();
        $list = $this->data($xilie_id, true);
        $this->assign('recommend', $recommend);
        $this->assign('xilie_id', $xilie_id);
        $this->assign('list', $list['list']);
        $this->assign('total', $list['total']);
        $this->assign('page', $list['page']);
        $this->assign('limit', $list['limit']);
        $param = input();
        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);
        return $this->fetch('admin@recommend/vodindex');
    }

    protected function data($xilie_id = 0)
    {
        $param = input();
        if ($xilie_id == 0) {
            $xilie_id = $param['xilie_id'];
        }
        $page = intval($param['page']) < 1 ? 1 : $param['page'];
        $limit = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $offset = $limit * ($page - 1);
        $where = [];
        if (isset($param['keyword'])) {
            $where['v.vod_name'] = ['like', '%' . $param['keyword'] . '%'];
            $this->assign('keyword', $param['keyword']);
        }
        $total = db('recommend_vod')->alias('ev')->join('__VOD__ v', 'v.vod_id=ev.vod_id', 'LEFT')->where($where)->where('recommend_id', $xilie_id)->count();
        $list = db('recommend_vod')->alias('ev')->join('__VOD__ v', 'v.vod_id=ev.vod_id', 'LEFT')
            ->where($where)
            ->where('ev.recommend_id', $xilie_id)
            ->order('ev.sort_manual', 'asc')
            ->order('ev.sort', 'asc')
            ->order('ev.time_added', 'desc')
            ->order('ev.id', 'desc')
            ->limit($offset, $limit)
            ->select();
        return [
            'code' => 1,
            'msg' => '数据列表',
            'page' => $page,
            'pagecount' => ceil($total / $limit),
            'limit' => $limit,
            'total' => $total,
            'list' => $list
        ];
    }

    public function addInrecommend()
    {
        $time = time();
        $data = input();
        $ids = $data['vod_ids'];
        $xilie_id = intval($data['id']);
        if ($xilie_id < 1) {
            $this->error('数据id 出错');
        }
        if (count($ids) < 1) {
            $this->error('没有需要处理的数据');
        }
        $vodIds = db('recommend_vod')->where('recommend_id', $xilie_id)->column('vod_id');
        $ids = array_diff($ids, $vodIds);
        if (empty($ids)) {
            $this->error('所选数据已经在该主题里面了');
        }
        $insertData = [];
        foreach ($ids as $id) {
            $insertData[] = [
                'vod_id' => $id,
                'recommend_id' => $xilie_id,
                'time_added' => $time,
                'sort_manual' => 1
            ];
        }

        $return = db('recommend_vod')->insertAll($insertData);
        if ($return !== false) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    public function del()
    {
        $param = input();
        $ids = $param['ids'];

        if (!empty($ids)) {
            $where = [];
            $where['id'] = ['in', $ids];
            $return = db('recommend_vod')->where($where)->delete();
            if ($return !== false) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败！');
            }
        }
        return $this->error('参数错误');
    }

    public function field()
    {
        $param = input();
        $ids = $param['ids'];
        $col = $param['col'];
        $val = $param['val'];
        $tab = $param['tab'];

        if (!empty($ids)) {
            $where = [];
            $where['id'] = ['in', $ids];
            $return = db($tab)->where($where)->setField($col, $val);
            if ($return !== false) {
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        return $this->error('参数错误');
    }

    public function info()
    {
        if (Request()->isPost()) {
            $param = input('post.');
            $where = [];
            if (isset($param['id'])) {
                $where['id'] = ['neq', $param['id']];
            }
            $exsitData = db('recommend')->where($where)->where('name', $param['name'])->find();
            if (!empty($exsitData)) {
                $this->error('标题已经存在，请修改');
            }
            if ($param['id'] > 0) {
                $return = db('recommend')->where('id', $param['id'])->update($param);
            } else {
                unset($param['id']);
                $param['time_added'] = time();
                $return = db('recommend')->insert($param);
            }
            if ($return !== false) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        }

        $id = input('xilie_id');
        $res = db('recommend')->where('id', $id)->find();
        $this->assign('info', $res);

        return $this->fetch('admin@recommend/info');
    }

    public function deleterecommend()
    {
        $id = input('ids');
        $res = db('recommend')->where('id', $id)->delete();
        db('recommend_vod')->where('recommend_id', $id)->delete();
        if ($res !== false) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }


    public function updateZongyi()
    {
        $xilie_id = 4;
        $listIds = db('vod')->where(['type_id|type_id_1' => 3])->order('vod_time', 'desc')->limit(50)->column(
            'vod_id'
        );
        $existIds = db('recommend_vod')->where('recommend_id', $xilie_id)->column('vod_id', 'id');
        //要删除的
        $deletedIds = array_diff($existIds, $listIds);
        if (!empty($deletedIds)) {
            db('recommend_vod')->where('sort_manual', 999)->where(
                'recommend_id',
                $xilie_id
            )->whereIn('vod_id', $deletedIds)->delete();
        }

        $insertIds = array_diff($listIds, $existIds);
        //要插入的
        $data = [];
        $time = time();
        $recommendVod = new RecommendVod();
        $insertData = [];
        foreach ($listIds as $key => $val) {
            if (in_array($val, $insertIds)) {
                $insertData[] = [
                    'recommend_id' => $xilie_id,
                    'sort' => $key + 1,
                    'time_added' => $time,
                    'vod_id' => $val
                ];
            } else {
                $updateData = [
                    'recommend_id' => $xilie_id,
                    'sort' => $key + 1,
                    'vod_id' => $val,

                ];
                $id = array_search($val, $existIds);
                $recommendVod->save($updateData, ['id' => $id]);
//                    $sql = $recommendVod->where('id', $id)->update($updateData);
            }
        }
        if (!empty($insertData)) {
            $recommendVod->insertAll($insertData);
        }
        $this->success('操作成功！');
    }

    public function cachesetting()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $xilie_id = $data['xilie_id'];
            $xilieInfo = db('recommend')->where('id', $xilie_id)->find();
            if (empty($xilieInfo)) {
                $this->error('数据有误!');
            }
            $ts_number = intval($data['ts_number']);
            $ts_offset = intval($data['ts_offset']);
            if ($ts_number < 1) {
                $this->error('缓存数量小于1，无需设置！');
            }
            db()->startTrans();
            try {
                //保存设置；
                db('recommend')->where('id', $xilie_id)->update([
                    'ts_number' => $ts_number,
                    'ts_offset' => $ts_offset
                ]);
                //查询未缓存的电影ID
                $vodIds = db('recommend_vod')->alias('ev')->join('__VOD__ v', 'v.vod_id=ev.vod_id', 'LEFT')->where('ev.recommend_id', $xilie_id)->where('v.is_cache', 0)->where('v.vod_id', '>', 0)->column('v.vod_id');
                if (!empty($vodIds)) {
                    foreach ($vodIds as $vodId) {
                        //标记缓存
                        $sql = db('vod')->where('vod_id', $vodId)->update(['is_cache' => 1]);
                        //写入任务数据库
                        db('m3u8_job')->insert(
                            [
                                'vod_id' => $vodId,
                                'vod_time' => time(),
                                'time_added' => time(),
                                'status' => 0,
                                'need_delete' => 1
                            ]
                        );
                        //写入缓存配置数据库
                        db('m3u8_setting')->insertGetId(
                            [
                                'time_added' => time(),
                                'vod_id' => $vodId,
                                'delete_start_index' => 0,
                                'number' => $data['ts_number'],
                                'delete_end_index' => $data['ts_offset'],
                            ]
                        );
                    }
                }
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                $this->error($e->getMessage(), null, $e->getTrace());
            }
            $this->success('操作成功！');

        } else {
            $xilie_id = input('xilie_id');
            $xilieInfo = db('recommend')->where('id', $xilie_id)->find();
            if (empty($xilieInfo)) {
                $this->error('数据有误!');
            }
            $this->assign('xilieInfo', $xilieInfo);
            return $this->fetch('admin@explore/allm3u8');
        }
    }

}